package com.pcbly.web.commons;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class MacfromMachine {
	public static String hexByte(byte b) {
		String s = "000000" + Integer.toHexString(b);
		return s.substring(s.length() - 2);
	}

	public static String getMacOnOther() {
		StringBuilder builder = new StringBuilder();
		try {
			Enumeration<NetworkInterface> el = NetworkInterface
					.getNetworkInterfaces();
			while (el.hasMoreElements()) {
				byte[] mac = el.nextElement().getHardwareAddress();
				if (mac == null)
					continue;

				for (byte b : mac) {
					builder.append(hexByte(b));
					builder.append("-");
				}
				builder.deleteCharAt(builder.length() - 1);
				System.out.println(builder);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return builder.toString();
	}

	public static String getMacOnWindow() {

		String address = "";
		String os = System.getProperty("os.name");
		if (os != null && os.startsWith("Windows")) {
			try {
				String command = "cmd.exe /c ipconfig /all";
				Process p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(p
						.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("Physical Address") > 0) {
						int index = line.indexOf(":");
						index += 2;
						address = line.substring(index);
						break;
					}
				}
				br.close();
				return address.trim();
			} catch (IOException e) {
			}
		}
		return address;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		String mac;
		if (args.length > 0)
			mac = args[0];// other mac address
		else
			mac = getMacOnWindow();// this mac address

		System.out.println(mac);// for mac address
		mac = getMacOnOther();// this mac address
		System.out.println(mac);// for mac address

	}
}
